package com.broada.apm.mysql.handler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import com.broada.apm.model.IPLocation;
import com.broada.apm.utils.ExceptionUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.io.LineProcessor;

public class IpLocationsImporter {
	private static Logger LOG = LoggerFactory.getLogger(IpLocationsImporter.class);
	
	@Autowired
	private static DataSource dataSource;
	
	private static JdbcTemplate jdbcTemplate = new JdbcTemplate();
	
	private static List<Map<String, String>> loadAreaMap(File path) throws IOException {
		final List<Map<String, String>> areas = Lists.newArrayList();
		com.google.common.io.Files.readLines(path, Charset.forName("utf-8"), new LineProcessor<List<Map<String, String>>>() {
			
			@Override
			public boolean processLine(String line) throws IOException {
				ObjectMapper om = new ObjectMapper();
				om.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
				@SuppressWarnings("unchecked")
				HashMap<String, String> r = om.readValue(line, HashMap.class);
				areas.add(r);
				return true;
			}

			@Override
			public List<Map<String, String>> getResult() {
				return areas;
			}
			
		});
		return areas;
	}

	public void test() throws IOException {
		String file = "D:\\svn\\apm\\global\\doc\\Vn.0.r1\\03.设计\\ip\\cn";
		importFromFile(new File("地图编码.json"), new File(file));
	}

	public static void importFromFile(File regionPath ,File path) throws IOException {
		final List<Map<String, String>> loadAreaMap = loadAreaMap(regionPath);
		final FileWriter fw = new FileWriter("iplocations.txt");
		final FileWriter err = new FileWriter("err.txt");
		final List<String> sqls = Lists.newArrayList();

		@SuppressWarnings("resource")
		ApplicationContext act = new ClassPathXmlApplicationContext("spring-data-context.xml");
		dataSource = (DataSource) act.getBean("dataSource");
		jdbcTemplate.setDataSource(dataSource);
		
		try  {
			com.google.common.io.Files.readLines(path, Charset.forName("utf-8"), new LineProcessor<Void>() {

				@Override
				public boolean processLine(final String l) throws IOException {
					try {
						// 1.1.4.0|1.1.7.255|16843776|16844799|中国|华东|福建省|福州市|电信||CN|300000|350000|350100|-1|100017
						String[] parts = l.split("\\|");
						String p = parts[6];
						String af = parts[7];
						if (p.length() == 0 || af.length() == 0){
							err.append(l).append("\n");						
							return true;
						}
						
						IPLocation loc = new IPLocation();
						loc.setStartIp(parts[0]);
						loc.setEndIp(parts[1]);
						loc.setStartIpNum(Long.parseLong(parts[2]));
						loc.setEndIpNum(Long.parseLong(parts[3]));
						loc.setId(String.format("%s-%s", parts[0], parts[1]));
						if (p.equals("内蒙古自治区"))
							p = "内蒙古";
						if (p.equals("西藏自治区"))
							p = "西藏";
						if (p.equals("广西壮族自治区"))
							p = "广西";
						if (p.equals("新疆维吾尔自治区"))
							p = "新疆";
						if (p.equals("宁夏回族自治区"))
							p = "宁夏";
						String pf = p;
						
						Map<String, String> province = null ;
						for (Iterator<Map<String, String>> iterator = loadAreaMap.iterator(); iterator.hasNext();) {
							Map<String, String> map = (Map<String, String>) iterator.next();
							if(map.get("name").equals(pf)) {
								province = map;
							}
						}
						if (province != null) {
							Map<String, String> eara = null;
							for (Map<String, String> map : loadAreaMap) {
								if(map.get("id").startsWith(province.get("id")) && map.get("name").equals(af)) {
									eara = map;
								}
							}
							if (eara != null) {
								loc.setAreaCode(eara.get("id"));
								
								StringBuffer sb = new StringBuffer();
								sb.append("insert into dict_ip_location (id, area_code, start_ip, end_ip");
								sb.append(", start_ip_num, end_ip_num, memo) values (");
								sb.append("'" + loc.getId() + "','" + loc.getAreaCode() + "',");
								sb.append("'" + loc.getStartIp() + "','" + loc.getEndIp() + "',");
								sb.append(loc.getStartIpNum() + "," + loc.getEndIpNum() + ",");
								sb.append("'" + loc.getMemo() + "')");
								
								sqls.add(sb.toString());
								
								fw.append(sb).append("\n");
							}
							if(sqls.size() > 1024) {
								jdbcTemplate.batchUpdate(sqls.toArray(new String[sqls.size()]));
								sqls.clear();
							}
						} else {
							err.append(l).append("\n");
						}
						return true;
					} catch (Exception e) {
						ExceptionUtils.error(LOG, "初始化地理位置数据发生错误", e);
					}
					return true;
				}

				@Override
				public Void getResult() {
					return null;
				}
				
			});
		} finally {
			if(sqls.size() > 0)
				jdbcTemplate.batchUpdate(sqls.toArray(new String[sqls.size()]));
			fw.close();
			err.close();
		}
	}
}
